package com.android.openapp.services;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.util.Log;

import com.android.openapp.R;
import com.android.openapp.data.Agriturismo;
import com.android.openapp.data.Architettura;
import com.android.openapp.data.Fiera;
import com.android.openapp.data.Museo;
import com.android.openapp.data.NLStorici;
import com.android.openapp.data.Ostello;
import com.android.openapp.data.Place;
import com.android.openapp.ui.MainActivity;
import com.android.openapp.ui.SettingsFragment;
import com.android.openapp.ui.Utils;
import com.socrata.api.HttpConnection;
import com.socrata.api.RequestException;
import com.socrata.api.Response;
import com.socrata.data.View;
import com.socrata.data.View.Column;
import com.socrata.util.Variables;

public class DownloadData extends AsyncTask<Boolean, String, Integer[]>{
		//Handler handler;
		
		/*public DownloadData(Handler handler) {
				this.handler=handler;
		}*/
		Context mUIContext;
		Context mServiceContext;
		HttpConnection mConnection;
		
		ProgressDialog pd;
		
		/**
		 * Costruttore che riceve il context della Activity
		 * Puo' essere usato per chiamare metodi della UI
		 * (creare Toast e Dialog)
		 * @param serviceContext il Service chiamante
		 * @param UIContext se presente, la Activity
		 */
		public DownloadData(Context serviceContext, Context UIContext, HttpConnection connection){
			mServiceContext = serviceContext;
			mUIContext = UIContext;
			mConnection = connection;
		}
		
		long distance;
		Double latitude;
		Double longitude;
		
		public void setDistance(long distance){
			this.distance = distance;
		}
		
		public void setCurrentLocation(Location loc){
			latitude = loc.getLatitude();
			longitude = loc.getLongitude();
		}
		
		@Override
		protected Integer[] doInBackground(Boolean... params) {
			Integer result=0;
			Integer cycle=0;
			
			ArrayList<Place> list=new ArrayList<Place>();
			
//    		String lat="45.8964306";
//    		String lng="9.6545868";
//    		Double latitude=45.8964306;
//    		Double longitude=9.6545868;
//    		
			String lat = Double.toString(latitude);
    		String lng = Double.toString(longitude);

			String range = Long.toString(distance);
    		
    		//da implemetare effettive coordinate
    		String provinciaAtt=HttpConnection.getProviciaByCoord(latitude, longitude);
    		
    		Log.d("DownloadData.class - distance",range);
    		/**
    		 * 
    		 * lat= 45.8964306
    		 * lng= 9.6545868
    		 * range= 10
    		 * 
    		 * 9897725
    		 * */
    		
    		for(int i=0;i<Place.datasetM.length;i++){
    			if (params[i]){
    				cycle++;
    				//Ricerca colonna di tipo 'Place'
    				Column lag=View.getColByDataType(Place.listmetadati.get(i),"location");
    				//Log.d("TEST", lag.getName());
    				if (lag!=null){
    					Log.d("TEST", "dataset#"+i+", column name "+lag.getName());
    					
    					String json =  "{query:{'originalViewId':"+Place.datasetM[i].toLowerCase()+",'name':"+Place.datasetM[i].toLowerCase()+","+
    					"'query':{" +
    					"'filterCondition':{" +
    					"'type':'operator'," +
    					"'value':'AND'," +
    					"'children':[" +
    					"{" +
    					"'type':'operator'," +
    					"'value':'WITHIN_CIRCLE'," +
    					"'children':[" +
    					"{'columnId':"+Integer.toString(lag.getId())+"," +
    					"'type':'column'" +
    					"}," +
    					"{" +
    					"'type':'literal'," +
    					"'value':"+lat+
    					"}," +
    					"{" +
    					"'type':'literal'," +
    					"'value':"+lng+
    					"}," +
    					"{" +
    					"'type':'literal'," +
    					"'value':"+range+
    					"}" +
    					"]" +
    					"}" +
    					"]" +
    					"}" +
    					"}" +
    					"}" +
    					"}";
    					Response r = mConnection.post("https://dati.lombardia.it/api/views/INLINE/rows.json?method=getRows&start=0&length=100",json);

    					//Log.d("fase2",Integer.toString(r.status));
    					if(r!=null){
    						result++;

    						try {

    							List<View.Row> row1 = Place.listmetadati.get(i).getRows(r);
    							//Log.d("fase2",Integer.toString(row1.size()));
    							//Log.d("fase2", Place.listmetadati.get(i).getId());
    							//Log.d("fase2", row1.get(0).getId());
    							Place loc = null;
    							for(View.Row temp : row1){

    								switch(i){
    								case 0: loc=new Museo(temp);
    								//Log.d("Museo",loc.getDenominazione());
    								break;
    								case 1: loc=new Ostello(temp);
    								break;
    								case 2: loc=new Architettura(temp);
    								break;
    								case 4: loc=new NLStorici(temp);
    								break;

    								}
    								if(loc != null)
    									list.add(loc);

    							}

    						} catch (RequestException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    					}
    				}
    			
    			else{
    				Log.v(MainActivity.TAG, "metadati #"+i+" non ancora pronti: getCol() ha ritornato null");
    				//Log.d("URL-get","https://dati.lombardia.it/api/views/"+Place.listmetadati.get(i).getId()+"/rows.json?method=getRows&start=0&length=100");
    				//Log.d("Provincia",provinciaAtt);
    				//Response r=mConnection.get("https://dati.lombardia.it/api/views/"+Place.listmetadati.get(i).getId()+"/rows.json?search="+provinciaAtt);
    					
    				Column lag2;
					
    				
					
					
					String subquery=
						"{"+
					          "'type': 'operator',"+
					          "'value': 'GREATER_THAN_OR_EQUALS',"+
					          "'children': ["+
					            "{"+
					              "'columnId': 9636173,"+
					              "'type': 'column'"+
					            "},"+
					            "{"+
					              "'type': 'literal',"+
					              "'value': '2012'"+
					            "}"+
					          "]"+
					        "},";
					if(i==3){
						lag2=Place.listmetadati.get(i).getColumnByIdentifier("CAP_COM_PRO");
						subquery="";
					}
						else
    					lag2=Place.listmetadati.get(i).getColumnByIdentifier("PROVINCIA");
					
					Log.d("Column",Integer.toString(lag2.getId()));
    				String query2=
    					"{query:{"+
    						  "'originalViewId': "+Place.datasetM[i].toLowerCase()+","+
    						  "'name':"+ Place.datasetM[i].toLowerCase()+","+
    						  "'query': {"+
    						    "'filterCondition': {"+
    						      "'type': 'operator',"+
    						      "'value': 'AND',"+
    						      "'children': ["+
    						      subquery+
    						        "{"+
    						          "'type': 'operator',"+
    						          "'value': 'CONTAINS',"+
    						          "'children': ["+
    						            "{"+
    						              "'columnId': "+Integer.toString(lag2.getId())+","+
    						              "'type': 'column'"+
    						            "},"+
    						            "{"+
    						              "'type': 'literal',"+
    						              "'value':"+ provinciaAtt+""+
    						            "}"+
    						          "]"+
    						        "}"+
    						      "]"+
    						    "}"+
    						  "}"+
    						  "}"+
    						"}";
    				
    				
    				
    				Response r = mConnection.post("https://dati.lombardia.it/api/views/INLINE/rows.json?method=getRows&start=0&length=100",query2);
    				
    				if(r!=null){
						result++;
						
						try {
							Log.i("index",Integer.toString(i));
							List<View.Row> row1 = Place.listmetadati.get(i).getRows(r);
							//Log.d("fase2",Integer.toString(row1.size()));
							//Log.d("fase2", Place.listmetadati.get(i).getId());
							//Log.d("fase2", row1.get(0).getId());
							Place loc = null;
							for(View.Row temp : row1){

								switch(i){
								case 3: loc=new Agriturismo(temp);
								//Log.d("Museo",loc.getDenominazione());
								break;
								case 5: 
									
									loc=new Fiera(temp);
								break;
								
								}
								
								if(loc != null && Controller.distanceTo(loc)<= distance)
									list.add(loc);

							}

						} catch (RequestException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
    			}
    			}
    		}
    		synchronized (Place.lista) {
    			Place.setPlaces(list);
    			Log.d("Sync lista","ok");
			}
    		Log.d("method: getNearPlaces","eseguito");
    		Integer[] array={result,cycle};
			return array;
		}
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			String text = mUIContext.getResources().getString(R.string.refresh);
			pd = ProgressDialog.show(mUIContext, null, text);
		}
		
		@Override
		protected void onPostExecute(Integer[] result) {
			// TODO Auto-generated method stub
			/*Message message=new Message();
			if(result==Place.datasetM.length){
				message.what = Variables.DOWNLOAD_FINISHED;
				message.arg1 = Variables.NO_ERROR;
			} else{
				message.what = Variables.DOWNLOAD_FINISHED;
				message.arg1 = Variables.DOWNLOAD_ERROR;
			}
			handler.sendMessage(message);*/
			super.onPostExecute(result);
			
			pd.dismiss();
			
			Intent i;
			if(result[0] == result[1]){
				i = new Intent(Variables.DOWNLOAD_FINISHED);
				i.putExtra(Variables.DOWNLOAD_RESULT, Variables.NO_ERROR);
				Utils.showToast(mUIContext, "Scaricamento Places eseguito con successo");
				result[0]=0;
				result[1]=0;
			}
			else{
				i = new Intent(Variables.DOWNLOAD_FINISHED);
				i.putExtra(Variables.DOWNLOAD_RESULT, Variables.DOWNLOAD_ERROR);
				Utils.showToast(mUIContext, "Scaricamento Places eseguito con errori");
				result[0]=0;
				result[1]=0;
			}
			mServiceContext.sendBroadcast(i);
		}
		
}

